import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Typography, 
  message, 
  Checkbox,
  Row, 
  Col, 
  Space,
  Tabs,
  Divider
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined,
  ShopOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTenantStore } from '../../stores/tenant';
import { useAuthStore } from '../../stores/auth';
import SimpleTenantSelector from '../../components/SimpleTenantSelector';
import './index.css';

const { Title, Text } = Typography;

// 系统用户登录表单
interface SystemLoginForm {
  username: string;
  password: string;
  remember?: boolean;
}

// 租户用户登录表单
interface TenantLoginForm {
  tenantCode: string;
  username: string;
  password: string;
  remember?: boolean;
}

type LoginMode = 'system' | 'tenant';

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [systemForm] = Form.useForm<SystemLoginForm>();
  const [tenantForm] = Form.useForm<TenantLoginForm>();
  const [loading, setLoading] = useState(false);
  const [loginMode, setLoginMode] = useState<LoginMode>('system');
  const [selectedTenant, setSelectedTenant] = useState<string>('');
  
  const { tenantLogin } = useTenantStore();
  const { login } = useAuthStore();

  // 检查URL参数，如果有tenant参数则默认显示租户登录
  useEffect(() => {
    const tenantParam = searchParams.get('tenant');
    if (tenantParam) {
      setLoginMode('tenant');
      setSelectedTenant(tenantParam);
    }
  }, [searchParams]);

  // 系统用户登录处理
  const handleSystemLogin = async (values: SystemLoginForm) => {
    setLoading(true);
    try {
      console.log('系统用户登录:', values);
      
      // 使用真实的后端接口
      await login({
        username: values.username,
        password: values.password,
        rememberMe: values.remember,
      });
      
      navigate('/dashboard');
    } catch (error) {
      // 错误已经在store中处理，这里不需要额外处理
      console.error('系统登录错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 租户用户登录处理
  const handleTenantLogin = async (values: TenantLoginForm) => {
    setLoading(true);
    try {
      console.log('租户用户登录:', values);
      
      if (!values.tenantCode) {
        message.error('请选择或输入租户代码');
        return;
      }
      
      // 使用真实的后端接口
      await tenantLogin({
        username: values.username,
        password: values.password,
        tenantCode: values.tenantCode,
        rememberMe: values.remember,
      });
      
      navigate('/dashboard');
    } catch (error) {
      // 错误已经在store中处理，这里不需要额外处理
      console.error('租户登录错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      {/* 背景装饰 */}
      <div className="login-background">
        <div className="bg-shape bg-shape-1"></div>
        <div className="bg-shape bg-shape-2"></div>
        <div className="bg-shape bg-shape-3"></div>
      </div>
      
      <Row justify="center" align="middle" style={{ minHeight: '100vh', padding: 24, position: 'relative', zIndex: 2 }}>
        <Col xs={24} sm={20} md={16} lg={12} xl={8} xxl={6}>
          <div className="login-content">
            {/* 登录卡片 */}
            <Card className="login-card">
              {/* Logo区域 */}
              <div className="login-brand">
                <Title level={1} className="brand-title">
                  Cat Cloud
                </Title>
              </div>
              
              {/* 登录方式选择 */}
              <Tabs 
                activeKey={loginMode} 
                onChange={(key) => setLoginMode(key as LoginMode)}
                centered
                className="login-tabs"
                items={[
                  {
                    key: 'system',
                    label: (
                      <span>
                        <SafetyCertificateOutlined />
                        系统用户登录
                      </span>
                    ),
                    children: (
                      <Form
                        form={systemForm}
                        name="systemLogin"
                        onFinish={handleSystemLogin}
                        autoComplete="on"
                        size="large"
                        layout="vertical"
                        className="login-form"
                      >
                        <Form.Item
                          label="用户名"
                          name="username"
                          style={{ marginBottom: 16 }}
                          rules={[
                            { required: true, message: '请输入用户名!' },
                            { min: 3, message: '用户名至少3个字符!' },
                          ]}
                        >
                          <Input
                            id="system-username"
                            name="username"
                            autoComplete="username"
                            prefix={<UserOutlined className="input-prefix-icon" />}
                            placeholder="请输入系统用户名"
                            className="login-input"
                          />
                        </Form.Item>

                        <Form.Item
                          label="密码"
                          name="password"
                          style={{ marginBottom: 16 }}
                          rules={[
                            { required: true, message: '请输入密码!' },
                            { min: 6, message: '密码至少6个字符!' },
                          ]}
                        >
                          <Input.Password
                            id="system-password"
                            name="password"
                            autoComplete="current-password"
                            prefix={<LockOutlined className="input-prefix-icon" />}
                            placeholder="请输入密码"
                            className="login-input"
                          />
                        </Form.Item>

                        <Form.Item style={{ marginBottom: 8 }}>
                          <Row justify="space-between" align="middle">
                            <Col>
                              <Form.Item name="remember" valuePropName="checked" noStyle>
                                <Checkbox className="remember-checkbox">记住我</Checkbox>
                              </Form.Item>
                            </Col>
                            <Col>
                              <Button type="link" className="forgot-password-link">
                                忘记密码？
                              </Button>
                            </Col>
                          </Row>
                        </Form.Item>

                        <Form.Item style={{ marginBottom: 16 }}>
                          <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading}
                            block
                            className="login-button"
                          >
                            {loading ? '登录中...' : '系统用户登录'}
                          </Button>
                        </Form.Item>
                      </Form>
                    )
                  },
                  {
                    key: 'tenant',
                    label: (
                      <span>
                        <ShopOutlined />
                        租户用户登录
                      </span>
                    ),
                    children: (
                      <Form
                        form={tenantForm}
                        name="tenantLogin"
                        onFinish={handleTenantLogin}
                        autoComplete="on"
                        size="large"
                        layout="vertical"
                        className="login-form"
                      >
                        <Form.Item
                          label="租户代码"
                          name="tenantCode"
                          style={{ marginBottom: 16 }}
                          rules={[
                            { required: true, message: '请选择或输入租户代码!' },
                          ]}
                          initialValue={selectedTenant}
                        >
                          <SimpleTenantSelector
                            value={selectedTenant || tenantForm.getFieldValue('tenantCode')}
                            onChange={(code: string) => {
                              setSelectedTenant(code);
                              tenantForm.setFieldValue('tenantCode', code);
                              if (code) {
                                message.info(`已选择租户：${code}`);
                              }
                            }}
                            placeholder="请选择或输入租户代码"
                          />
                        </Form.Item>

                        <Form.Item
                          label="用户名"
                          name="username"
                          style={{ marginBottom: 16 }}
                          rules={[
                            { required: true, message: '请输入用户名!' },
                            { min: 3, message: '用户名至少3个字符!' },
                          ]}
                        >
                          <Input
                            id="tenant-username"
                            name="username"
                            autoComplete="username"
                            prefix={<UserOutlined className="input-prefix-icon" />}
                            placeholder="请输入租户用户名"
                            className="login-input"
                          />
                        </Form.Item>

                        <Form.Item
                          label="密码"
                          name="password"
                          style={{ marginBottom: 16 }}
                          rules={[
                            { required: true, message: '请输入密码!' },
                            { min: 6, message: '密码至少6个字符!' },
                          ]}
                        >
                          <Input.Password
                            id="tenant-password"
                            name="password"
                            autoComplete="current-password"
                            prefix={<LockOutlined className="input-prefix-icon" />}
                            placeholder="请输入密码"
                            className="login-input"
                          />
                        </Form.Item>

                        <Form.Item style={{ marginBottom: 8 }}>
                          <Row justify="space-between" align="middle">
                            <Col>
                              <Form.Item name="remember" valuePropName="checked" noStyle>
                                <Checkbox className="remember-checkbox">记住我</Checkbox>
                              </Form.Item>
                            </Col>
                            <Col>
                              <Button type="link" className="forgot-password-link">
                                忘记密码？
                              </Button>
                            </Col>
                          </Row>
                        </Form.Item>

                        <Form.Item style={{ marginBottom: 16 }}>
                          <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading}
                            block
                            className="login-button"
                          >
                            {loading ? '登录中...' : '租户用户登录'}
                          </Button>
                        </Form.Item>
                      </Form>
                    )
                  }
                ]}
              />
              
              <Divider />
              
              <div className="login-footer">
                <Space direction="vertical" size="small" style={{ width: '100%', textAlign: 'center' }}>
                  <Text className="footer-text">
                    © 2025 CatCloud. 保留所有权利
                  </Text>
                </Space>
              </div>
            </Card>
          </div>
        </Col>
      </Row>
    </div>
  );
};

export default Login;